<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';

// 天地图API密钥 - 请替换为你们的企业级密钥
const TIANDITU_KEY = 'b1ea1131dcf39baf49a8c8b1e0116991';
const dateStr = ref('');
const timeStr = ref('');
const city = ref('正在定位...');
const isLoading = ref(true);
const isError = ref(false);

// 格式化时间数字，补零
const formatNumber = (n: number): string => {
  return n < 10 ? `0${n}` : `${n}`;
};

// 更新时间显示
const updateTime = () => {
  const now = new Date();

  // 更新日期部分
  const year = now.getFullYear();
  const month = formatNumber(now.getMonth() + 1);
  const day = formatNumber(now.getDate());
  dateStr.value = `${year}年${month}月${day}日`;

  // 更新时间部分
  const hour = formatNumber(now.getHours());
  const minute = formatNumber(now.getMinutes());
  const second = formatNumber(now.getSeconds());
  timeStr.value = `${hour}:${minute}:${second}`;
};

// 获取当前城市地址 - 使用天地图API
const getCity = async () => {
  try {
    isLoading.value = true;
    isError.value = false;

    // 使用浏览器原生定位获取经纬度
    getCurrentPosition();
  } catch (error) {
    console.error('定位失败:', error);
    isError.value = true;
    city.value = '定位失败';
    ElMessage.error('获取位置信息失败');
  } finally {
    isLoading.value = false;
  }
};

// 获取当前位置
const getCurrentPosition = async () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    console.warn('浏览器不支持地理定位');
    // 使用默认坐标（济南市）
    try {
      const cityInfo = await tiandituReverseGeocode(36.798747059, 117.140035075);
      city.value = cityInfo.city || cityInfo.province || '未知城市';
    } catch (error) {
      console.error('默认坐标逆地理编码失败:', error);
      city.value = '定位失败';
      isError.value = true;
    } finally {
      isLoading.value = false;
    }
  }
};

// 定位成功回调
const showPosition = async (position) => {
  try {
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;

    console.log('获取到坐标:', { latitude: lat, longitude: lng });

    // 使用天地图逆地理编码获取城市信息
    const cityInfo = await tiandituReverseGeocode(lat, lng);
    city.value = cityInfo.city || cityInfo.province || '未知城市';
  } catch (error) {
    console.error('逆地理编码失败:', error);
    city.value = '定位失败';
    isError.value = true;
  } finally {
    isLoading.value = false;
  }
};

// 定位失败回调
const showError = async (error) => {
  console.error('定位失败:', error);

  switch (error.code) {
    case error.PERMISSION_DENIED:
      console.warn('用户拒绝了地理位置请求');
      break;
    case error.POSITION_UNAVAILABLE:
      console.warn('位置信息不可用');
      break;
    case error.TIMEOUT:
      console.warn('获取位置信息超时');
      break;
    case error.UNKNOWN_ERROR:
      console.warn('发生未知错误');
      break;
  }

  // 使用默认坐标（济南市）作为备用方案
  try {
    const cityInfo = await tiandituReverseGeocode(36.798747059, 117.140035075);
    city.value = cityInfo.city || cityInfo.province || '未知城市';
  } catch (fallbackError) {
    console.error('备用方案也失败了:', fallbackError);
    city.value = '定位失败';
    isError.value = true;
  } finally {
    isLoading.value = false;
  }
};

// 天地图逆地理编码
const tiandituReverseGeocode = async (lat: number, lng: number) => {
  try {
    const postStr = JSON.stringify({
      lon: lng,
      lat: lat,
      ver: 1
    });

    const url = `https://api.tianditu.gov.cn/geocoder?postStr=${encodeURIComponent(postStr)}&type=geocode&tk=${TIANDITU_KEY}`;

    console.log('天地图逆地理编码请求:', url);

    const response = await fetch(url);
    const data = await response.json();

    console.log('天地图逆地理编码响应:', data);

    if (data.status === '0' && data.result) {
      const addressComponent = data.result.addressComponent;
      return {
        city: addressComponent.city || addressComponent.district,
        province: addressComponent.province,
        district: addressComponent.district,
        country: addressComponent.country
      };
    }

    throw new Error(data.msg || '天地图逆地理编码失败');
  } catch (error) {
    console.error('天地图逆地理编码API请求失败:', error);
    throw error;
  }
};

// 定时器ID
let timer: number;

onMounted(() => {
  // 立即更新时间
  updateTime();
  // 设置定时器每秒更新
  timer = window.setInterval(updateTime, 1000);

  // 获取城市信息
  getCity();
});

onUnmounted(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<template>
  <div class="time-display">
    <div class="date">{{ dateStr }}</div>
    <div class="time">{{ timeStr }}</div>
    <div class="location" :class="{ 'error': isError, 'loading': isLoading }">
      <el-icon v-if="isLoading" class="loading-icon">
        <el-icon-loading />
      </el-icon>
      {{ city }}
    </div>
  </div>
</template>

<style scoped lang="scss">
.time-display {
  position: absolute;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding: 20px;
  color: white;
  z-index: 6;
  right: 1%;
  top: 1%;

  .date {
    font-size: 18px;
    font-weight: 500;
  }

  .time {
    font-size: 20px;
    color: #0ff;
    margin: 0 20px;
    font-family: PangMenZhengDao;
    width: 100px;
    text-align: center;
  }

  .location {
    display: flex;
    align-items: center;
    font-size: 16px;

    &.loading {
      color: white;
    }

    &.error {
      color: #f56c6c;
    }

    .loading-icon {
      animation: rotating 2s linear infinite;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
